layout = window.layout || {};
var locate = window.location;
layout.protocol = locate.protocol;
layout.mobile = true;
layout.desktop = layout;
layout.session = layout.session || {};
var href = locate.href;
if (href.indexOf("debugger") != -1) layout.debugger = true;
o2.addReady(function () {
    o2.load(["../o2_lib/mootools/plugin/mBox.Notice.js", "../o2_lib/mootools/plugin/mBox.Tooltip.js"], { "sequence": true }, function () {
        //MWF.defaultPath = "/x_desktop"+MWF.defaultPath;
        MWF.loadLP("zh-cn");
        MWF.require("MWF.xDesktop.Common", null, false);
        MWF.require("MWF.widget.Mask", null, false);

        layout.mask = new MWF.widget.Mask({ "style": "desktop" });
        layout.mask.load();

        MWF.require("MWF.xDesktop.Layout", function () {
            MWF.require("MWF.xDesktop.Authentication", null, false);
            MWF.require("MWF.xAction.RestActions", null, false);
            (function () {
                layout.load = function () {
                    if (this.isAuthentication()) {
                        //var preview = window.frameElement.retrieve("preview");
                        //layout.desktop = window.frameElement.ownerDocument.window.layout.desktop;
                        //
                        this.node = $("layout");
                        this.content = $(document.body);
                        this.path = "/x_component_cms_Document/$Main/";
                        this.cssPath = "/x_component_cms_Document/$Main/default/css.wcss";
                        this._loadCss();

                        // MWF.require("MWF.xDesktop.MessageMobile", function(){
                        //     layout.message = new MWF.xDesktop.MessageMobile();
                        //     layout.message.load();
                        // }.bind(this));


                        //MWF.xDesktop.requireApp("cms.Document", "Actions.RestActions", null, false);
                        //this.action = new MWF.xApplication.cms.Document.Actions.RestActions();
                        this.action = MWF.Actions.get("x_cms_assemble_control");
                        MWF.xDesktop.requireApp("cms.Document", "lp." + MWF.language, null, false);
                        //MWF.xDesktop.requireApp("cms.Document", "lp."+MWF.language, {
                        //    "onRequestFailure": function(){
                        //        MWF.xDesktop.requireApp("cms.Document", "lp.zh-cn", null, false);
                        //    }.bind(this),
                        //    "onSuccess": function(){}.bind(this)
                        //}, false);

                        this.lp = MWF.xApplication.cms.Document.LP;

                        this.options = this.getIds();
                        this.options.name = "cms.Document";
                        this.loadDocument(this.options);

                        //MWF.require("MWF.xApplication.process.Xform.Form", function(){
                        //    layout.appForm = new MWF.APPForm($("layout"), preview.data);
                        //    layout.appForm.load();
                        //});
                    }
                };
                layout.addEvent = function () { };
                layout.close = function () {
                    if (window.o2android && window.o2android.closeDocumentWindow) {
                        window.o2android.closeDocumentWindow('close');
                    }
                    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.closeDocumentWindow) {
                        window.webkit.messageHandlers.closeDocumentWindow.postMessage('close');
                    }
                };
                layout._loadCss = function () {
                    var key = encodeURIComponent(this.cssPath);
                    if (MWF.widget.css[key]) {
                        this.css = MWF.widget.css[key];
                    } else {
                        var r = new Request.JSON({
                            url: this.cssPath,
                            secure: false,
                            async: false,
                            method: "get",
                            noCache: false,
                            onSuccess: function (responseJSON, responseText) {
                                this.css = responseJSON;
                                MWF.widget.css[key] = responseJSON;
                            }.bind(this),
                            onError: function (text, error) {
                                alert(error + text);
                            }
                        });
                        r.send();
                    }
                };
                layout.getIds = function () {
                    var href = window.location.href;
                    var qStr = href.substr(href.indexOf("?") + 1, href.length);
                    var qDatas = qStr.split("&");
                    var obj = {};
                    qDatas.each(function (d) {
                        var q = d.split("=");
                        obj[q[0].toLowerCase()] = q[1];
                    });
                    return obj;
                };

                layout.loadDocument = function (options) {
                    // this.action.viewDocument( options.id, function(document){

                    o2.Actions.invokeAsync([
                        { "action": this.action, "name": "getDocument" },
                        { "action": this.action, "name": "listAttachment" }
                    ], {
                        "success": function (json_document, json_att) {
                            if (this.mask) this.mask.hide();
                            if (json_document) {
                                if (json_att && typeOf(json_att.data) === "array") {
                                    json_document.data.attachmentList = json_att.data;
                                } else {
                                    json_document.data.attachmentList = [];
                                }
                                this.parseData(json_document.data);
                                if (!this.formId || this.formId === "") {
                                    this.notice(this.document.categoryName + this.lp.formNotSetted, "error");
                                } else {
                                    this.loadForm(this.formId);
                                }
                            } else {
                                this.notice(this.lp.documentGettedError + ":" + error.responseText, "error");
                                this.close();
                            }
                        }.bind(this), "failure": function () {
                            this.notice(this.lp.documentGettedError + ":" + error.responseText, "error");
                            this.close();
                        }.bind(this)
                    }, options.id);

                    //this.action.getDocument( options.id, function(document){
                    //    if (this.mask) this.mask.hide();
                    //    this.parseData(document.data);
                    //    if( !this.formId || this.formId==="" ){
                    //        this.notice(  this.document.categoryName + this.lp.formNotSetted , "error");
                    //    }else{
                    //        this.loadForm( this.formId );
                    //    }
                    //}.bind(this), null);
                };

                //layout.loadDocument = function(options){
                //    this.action.getDocument( options.id, function(document){
                //        if (this.mask) this.mask.hide();
                //        this.parseData(document.data);
                //        this.action.getCategory( this.document.categoryId, function( js ){
                //            this.categoryData = js.data;
                //            var formId = this.categoryData.formId || this.categoryData.readFormId;
                //            if( this.readonly == true && this.categoryData.readFormId && this.categoryData.readFormId != "" ){
                //                formId = this.categoryData.readFormId;
                //            }
                //            if( !formId || formId=="" ){
                //                this.notice(  this.document.categoryName + this.lp.formNotSetted , "error");
                //            }else{
                //                this.loadForm( formId );
                //            }
                //        }.bind(this))
                //    }.bind(this), null);
                //};

                layout.loadForm = function (formId) {
                    this.action.getForm(formId, function (json) {
                        //if (this.mask) this.mask.hide();
                        this.form = (json.data.mobileData) ? JSON.decode(MWF.decodeJsonString(json.data.mobileData)) : null;
                        if (!this.form) {
                            this.form = (json.data.data) ? JSON.decode(MWF.decodeJsonString(json.data.data)) : null;
                        }
                        //this.listAttachment();
                        if (this.mask) this.mask.hide();
                        // this.attachmentList = [];
                        this.openDocument();
                    }.bind(this), function (error) {
                        if (this.mask) this.mask.hide();
                        this.notice(this.lp.formGettedError + ":" + error.responseText, "error");
                        //this.close();
                    }.bind(this));
                };

                //layout.listAttachment = function(){
                //    if( this.document.attachmentList && this.document.attachmentList.length > 0 ){
                //        this.action.listAttachment(this.document.id, function( json ){
                //            if (this.mask) this.mask.hide();
                //            this.attachmentList = json.data;
                //            this.attachmentList.each(function(att){
                //                att.lastUpdateTime = att.updateTime;
                //                att.person = att.creatorUid;
                //            })
                //            this.openDocument();
                //        }.bind(this), function(error){
                //            this.notice(  this.lp.attachmentGettedError  + ":" + error.responseText, "error");
                //            this.close();
                //        }.bind(this));
                //    }else{
                //        if (this.mask) this.mask.hide();
                //        this.attachmentList = [];
                //        this.openDocument();
                //    }
                //},

                layout.errorDocument = function () {
                    if (this.mask) this.mask.hide();
                    this.node.set("text", "openError");
                };
                layout.parseData = function (data) {
                    window.document.title = data.document.title;

                    data.document.subject = data.document.title;
                    this.data = data.data;
                    this.document = data.document;
                    this.attachmentList = data.attachmentList || [];
                    this.attachmentList.each(function (att) {
                        att.lastUpdateTime = att.updateTime;
                        att.person = att.creatorUid;
                    });


                    //控制权限
                    var isControl = false;
                    if (data.isAppAdmin) {//应用管理员
                        isControl = true;
                    }
                    if (data.isCategoryAdmin) {//分类管理员
                        isControl = true;
                    }
                    if (data.isManager) {//管理员
                        isControl = true;
                    }
                    if (data.isCreator) {//创建者
                        isControl = true;
                    }
                    if (data.isEditor) { //编辑权限
                        isControl = true;
                    }
                    if (this.options.readonly === false) {
                        this.readonly = false;
                    } else {
                        this.readonly = true;
                        if (this.document.docStatus === "draft") {
                            this.readonly = false
                        }
                    }

                    this.formId = this.document.form || this.document.readFormId;
                    //当前模式 阅读还是编辑 移动端上使用
                    var currentMode = "read";
                    if (this.readonly === true && this.document.readFormId && this.document.readFormId !== "") {
                        this.formId = this.document.readFormId; //阅读表单
                        currentMode = "read";
                    } else {
                        this.formId = this.document.form;//编辑表单
                        currentMode = "edit";
                    }

                    this.control = data.control || {
                        "allowRead": true,
                        "allowPublishDocument": isControl && this.document.docStatus === "draft",
                        "allowSave": isControl && this.document.docStatus === "published",
                        "allowPopularDocument": false,
                        "allowEditDocument": isControl,
                        "allowDeleteDocument": isControl,
                        "allowArchiveDocument": false,
                        "allowRedraftDocument": false,
                        "currentMode": currentMode
                    };
                };
                layout.openDocument = function () {
                    if (this.form) {
                        MWF.xDesktop.requireApp("cms.Xform", "Form", function () {
                            this.appForm = new MWF.CMSForm(this.node, this.form, {
                                "readonly": this.readonly,
                                "autoSave": !this.readonly,
                                "saveOnClose": false,
                                "showAttachment": true,
                                "onPostPublish": null
                            });
                            this.appForm.businessData = {
                                "data": this.data,
                                "document": this.document,
                                "control": this.control,
                                "attachmentList": this.attachmentList,
                                "status": {
                                    //"readonly": (this.options.readonly) ? true : false
                                    "readonly": this.readonly
                                },
                                //work.job 图片编辑器控件 使用上传图片到云盘的关联id
                                "work": {
                                    "referencetype": "cmsDocument",
                                    "job": this.document.id
                                }
                            };
                            this.appForm.documentAction = this.action;
                            this.appForm.app = this;
                            this.appForm.load(function () {
                                console.log('加载表单完成。。。。。。。。。。。。。');
                                //告诉移动端表单加载完成
                                if (window.o2android && window.o2android.cmsFormLoaded) {
                                    layout.appForm = this.appForm;
                                    window.o2android.cmsFormLoaded(JSON.stringify(this.control));
                                }
                                if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cmsFormLoaded) {
                                    layout.appForm = this.appForm;
                                    window.webkit.messageHandlers.cmsFormLoaded.postMessage(JSON.stringify(this.control));
                                }
                            }.bind(this));
                        }.bind(this));
                    }
                };

                layout.isAuthentication = function () {
                    layout.authentication = new MWF.xDesktop.Authentication({
                        "onLogin": layout.load.bind(layout)
                    });

                    var returnValue = true;
                    this.authentication.isAuthenticated(function (json) {
                        this.user = json.data;
                        layout.session.user = json.data;
                    }.bind(this), function () {
                        // if (layout.config.loginPage && layout.config.loginPage.enable && layout.config.loginPage.portal){
                        //     MWF.xDesktop.loadPortal(layout.config.loginPage.portal);
                        // }else{
                        //     this.authentication.loadLogin(document.body);
                        // }

                        this.authentication.loadLogin(this.node);
                        returnValue = false;
                    }.bind(this));
                    return returnValue;
                };
                //layout.getServiceAddress = function(callback){
                //    var host = layout.config.center.host || window.location.hostname;
                //    var port = layout.config.center.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                //layout.getServiceAddress = function(callback){
                //    if (typeOf(layout.config.center)=="object"){
                //        this.getServiceAddressConfigObject(callback);
                //    }else if (typeOf(layout.config.center)=="array"){
                //        this.getServiceAddressConfigArray(callback);
                //    }
                //
                //};
                //layout.getServiceAddressConfigArray = function(callback) {
                //    var requests = [];
                //    layout.config.center.each(function(center){
                //        requests.push(
                //            this.getServiceAddressConfigObject(function(){
                //                requests.each(function(res){
                //                    if (res.isRunning()){res.cancel();}
                //                });
                //                if (callback) callback();
                //            }.bind(this), center)
                //        );
                //    }.bind(this));
                //};
                //layout.getServiceAddressConfigObject = function(callback, center){
                //    var centerConfig = center;
                //    if (!centerConfig) centerConfig = layout.config.center;
                //    var host = centerConfig.host || window.location.hostname;
                //    var port = centerConfig.port;
                //    var uri = "";
                //    if (!port || port=="80"){
                //        uri = "http://"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }else{
                //        uri = "http://"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
                //    }
                //    var currenthost = window.location.hostname;
                //    uri = uri.replace(/{source}/g, currenthost);
                //    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";
                //    return MWF.restful("get", uri, null, function(json){
                //        this.serviceAddressList = json.data;
                //        this.centerServer = center;
                //        if (callback) callback();
                //    }.bind(this));
                //};
                layout.confirm = function (type, e, title, text, width, height, ok, cancel, callback, mask, style) {
                    MWF.require("MWF.xDesktop.Dialog", function () {
                        var size = this.content.getSize();
                        var x = 0;
                        var y = 0;
                        if (typeOf(e) == "element") {
                            var position = e.getPosition(this.content);
                            x = position.x;
                            y = position.y;
                        } else {
                            if (Browser.name == "firefox") {
                                x = parseFloat(e.event.clientX);
                                y = parseFloat(e.event.clientY);
                            } else {
                                x = parseFloat(e.event.x);
                                y = parseFloat(e.event.y);
                            }


                            //    if (!x || !y){
                            if (e.target) {
                                var position = e.target.getPosition(this.content);
                                x = position.x;
                                y = position.y;
                            }
                            //    }
                        }

                        if (x + parseFloat(width) > size.x) {
                            x = x - parseFloat(width);
                        }
                        if (x < 0) x = 0;
                        if (y + parseFloat(height) > size.y) {
                            y = y - parseFloat(height);
                        }
                        if (y < 0) y = 0;

                        var ctext = "";
                        var chtml = "";
                        if (typeOf(text).toLowerCase() == "object") {
                            ctext = text.text;
                            chtml = text.html;
                        } else {
                            ctext = text;
                        }
                        var dlg = new MWF.xDesktop.Dialog({
                            "title": title,
                            "style": style || "flat",
                            "top": y,
                            "left": x - 20,
                            "fromTop": y,
                            "fromLeft": x - 20,
                            "width": width,
                            "height": height,
                            "text": ctext,
                            "html": chtml,
                            "container": this.content,
                            "maskNode": mask,
                            "buttonList": [
                                {
                                    "text": MWF.LP.process.button.ok,
                                    "action": ok
                                },
                                {
                                    "text": MWF.LP.process.button.cancel,
                                    "action": cancel
                                }
                            ]
                        });

                        switch (type.toLowerCase()) {
                            case "success":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "error":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "info":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            case "warn":
                                dlg.content.setStyle("background-image", "url()");
                                break;
                            default:
                            //dlg.content.setStyle("background-image", "");
                        }
                        dlg.show();
                        if (callback) callback(dlg);
                    }.bind(this));
                };
                layout.notice = function (content, type, target, where, offset) {
                    if (!where) where = { "x": "right", "y": "top" };
                    if (!target) target = this.content;
                    if (!type) type = "ok";
                    var noticeTarget = target || $(document.body);
                    var off = offset;
                    if (!off) {
                        off = {
                            x: 10,
                            y: where.y.toString().toLowerCase() == "bottom" ? 10 : 10
                        };
                    }

                    new mBox.Notice({
                        type: type,
                        position: where,
                        move: false,
                        target: noticeTarget,
                        delayClose: (type == "error") ? 10000 : 5000,
                        offset: off,
                        content: content
                    });
                };
                layout.reload = function () {
                    window.location.reload();
                };

                MWF.getJSON("res/config/config.json", function (config) {
                    layout.config = config;

                    MWF.xDesktop.getServiceAddress(layout.config, function (service, center) {
                        layout.serviceAddressList = service;
                        layout.centerServer = center;
                        layout.load();
                    }.bind(this));
                    //layout.getServiceAddress(function(){
                    //    layout.load();
                    //});
                });
            })();

        });
    });
});